package com.windea.study.kotlin.jvm.crypt.sections

import javax.crypto.*
import javax.crypto.spec.*
import kotlin.test.*

class DesCryptTest {
	@Test
	fun test() {
		val input = "hello world"
		val key = "12345678"
		
		val factory = SecretKeyFactory.getInstance("DES")
		
		val desKeySpec = DESKeySpec(key.toByteArray()) //传入自己的密钥
		val keySecret = factory.generateSecret(desKeySpec)
		
		val cipher = Cipher.getInstance("DES")
		cipher.init(Cipher.ENCRYPT_MODE, keySecret)
		val result = cipher.doFinal(input.toByteArray())
		println("加密后结果：$result")
	}
	
	@Test
	fun test2() {
		//中文会导致解密乱码
		//在UTF-8中，一个中文3个字节，两个中文6个字节
		//加密后两个中文会变成8个字节，到编码表中找不到
		//解决方法：使用Base64进行编码解码
		val input = "你好，世界！"
		val key = "88888888"
		val encrypted = DesCrypt.encrypt(input, key)
		println(encrypted)
		val decrypted = DesCrypt.decrypt(encrypted, key)
		println(decrypted)
	}
}
